package com.ligongmusic.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.http.NameValuePair;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.ConnectivityManager;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;


/**
 * 网络相关工具类
 */
@SuppressWarnings("deprecation")
public class NetWorkUtils {
    private static ExecutorService executor = Executors.newCachedThreadPool();

    /**
     * 获取网络连接是否可用
     *
     * @param mContext
     * @return
     */
    public static boolean isNetworkAvailable(Context mContext) {
        ConnectivityManager manager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager != null && manager.getActiveNetworkInfo() != null)
            return manager.getActiveNetworkInfo().isAvailable();
        return false;
    }

    /**
     * 当网络无连接时设置网络
     *
     * @param mContext
     */
    public static void setNetWork(final Context mContext) {
        // 提示对话框
        AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                mContext);
        builder.setTitle("网络设置提示")
                .setMessage("网络连接不可用,是否进行设置?")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = null;
                        // 判断手机系统的版本 即API大于10 就是3.0或以上版本
                        if (android.os.Build.VERSION.SDK_INT > 10) {
                            intent = new Intent(
                                    android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                        } else {
                            intent = new Intent();
                            ComponentName component = new ComponentName(
                                    "com.android.settings",
                                    "com.android.settings.WirelessSettings");
                            intent.setComponent(component);
                            intent.setAction("android.intent.action.VIEW");
                        }
                        mContext.startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    public static void uploadFile(final String url, final Map<String, Object> maps, NetWorkCallBack callBack) {
        Future<String> future = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                StringBuffer buffer = new StringBuffer();
                URL uri = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) uri
                        .openConnection();
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");
                conn.setUseCaches(false);
                conn.setInstanceFollowRedirects(true);
                // 进行编码
                conn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                conn.connect();
                DataOutputStream os = new DataOutputStream(conn
                        .getOutputStream());
                StringBuffer content = new StringBuffer();
//				content.append("token=" + GlobalParams.token);
                Set<String> keySet = maps.keySet();
                for (String key : keySet) {
                    if (maps.get(key) instanceof Bitmap) {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        CompressFormat format = CompressFormat.JPEG;
                        Bitmap bitmap = (Bitmap) maps.get(key);
                        bitmap.compress(format, 100, bos);
                        InputStream is = new ByteArrayInputStream(bos.toByteArray());
                        StringBuffer temp = new StringBuffer();
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(is));
                        String line = null;
                        while ((line = reader.readLine()) != null)
                            temp.append(line + "\n");
                        content.append("&" + key + "=" + temp.toString());
                    } else if (maps.get(key) instanceof File) {
                        File file = (File) maps.get(key);
                        ByteArrayOutputStream bos = getBytes(file);
                        InputStream is = new ByteArrayInputStream(bos.toByteArray());
                        StringBuffer temp = new StringBuffer();
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(is));
                        String line = null;
                        while ((line = reader.readLine()) != null)
                            temp.append(line + "\n");
                        content.append("&" + key + "=" + temp.toString());
                    } else {
                        content.append(key + "=" + maps.get(key));
                    }
                }
                os.writeBytes(content.toString());
                os.flush();
                os.close();
                if (conn.getResponseCode() == 200) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null)
                        buffer.append(line);
                    return buffer.toString();
                }
                return null;
            }
        });
        try {
            String data = future.get();
            if (data != null)
                callBack.success(data);
            else
                callBack.error();
        } catch (InterruptedException e) {
            callBack.error(e.getMessage());
        } catch (ExecutionException e) {
            callBack.error(e.getMessage());
        }

    }

    /**
     * 将Bitmap对象转换成字符串
     */
    public static String bitmap2InputStream(Bitmap bitmap) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        CompressFormat format = CompressFormat.JPEG;
        bitmap.compress(format, 100, bos);
        InputStream is = new ByteArrayInputStream(bos.toByteArray());
        // 创建字节输出流对象
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // 定义读取的长度
        int len = 0;
        // 定义缓冲区
        byte buffer[] = new byte[1024 * 4];
        // 按照缓冲区的大小，循环读取
        while ((len = is.read(buffer)) != -1) {
            // 根据读取的长度写入到os对象中
            os.write(buffer, 0, len);
        }
        // 释放资源
        is.close();
        os.close();
        return os.toByteArray().toString();
    }

    /**
     * POST请求
     */
//    public static void postRequest(final List<NameValuePair> pairs, final String url, final NetWorkCallBack callBack) {
//        executor.execute(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient client = new OkHttpClient();
//                    FormBody.Builder builder = new FormBody.Builder();
//                    for (NameValuePair pair : pairs)
//                        builder.add(pair.getName(), pair.getValue());
//                    FormBody build = builder.build();
//                    Request request = new Request.Builder().post(build).url(url).build();
//                    Response response = client.newCall(request).execute();
//                    if (response.code() == 200)// 请求成功
//                        callBack.success(response.body().string());
//                    else
//                        callBack.error();
//                } catch (IOException e) {
//                    callBack.error(e.getMessage());
//                }
//            }
//        });
//
//    }


	public static void postRequest(final List<NameValuePair> pairs,
			final String url, final NetWorkCallBack callBack) {
		RequestParams params = new RequestParams();
		for (int i = 0; i < pairs.size(); i++) {
			params.addBodyParameter(pairs.get(i).getName(), pairs.get(i).getValue());
		}
		HttpUtils hu = new HttpUtils();
//		hu.configTimeout(5000);
		hu.configCurrentHttpCacheExpiry(0);
		hu.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				callBack.success(responseInfo.result);
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				callBack.error(msg);
			}
		});
//		Future<String> future = executor.submit(new Callable<String>() {
//			@Override
//			public String call() throws Exception {
//				StringBuffer buffer = new StringBuffer();
//				URL uri = new URL(url);
//				HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
//				conn.setDoOutput(true);
//				conn.setDoInput(true);
//				conn.setRequestMethod("POST");
//				conn.setUseCaches(false);
//				conn.setInstanceFollowRedirects(true);
//				// 进行编码
//		        conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
//		        conn.connect();
//		        DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//		        StringBuffer content = new StringBuffer();
//		        for (int i = 0; i < pairs.size(); i++) {
//		        	if(i == 0)
//		        		content.append(pairs.get(i).getName() + "=" + pairs.get(i).getValue());
//		        	else
//		        		content.append("&" + pairs.get(i).getName() + "=" + pairs.get(i).getValue());
//				}
//		        os.writeBytes(content.toString());
//		        os.flush();
//		        os.close();
//		        if(conn.getResponseCode() == 200){
//			        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//			        String line;
//			        while ((line = reader.readLine()) != null)
//			           	buffer.append(line);
//					return buffer.toString();
//				}
//				return null;
//			}
//		});
//		try {
//			String data = future.get();
//			if(data != null)
//				callBack.success(data);
//			else
//				callBack.error();
//		} catch (InterruptedException e) {
//			callBack.error(e.getMessage());
//		} catch (ExecutionException e) {
//			callBack.error(e.getMessage());
//		}
	}


    public static <T> void uploadInfo(String fileType, String url,
                                      Map<String, T> param, RequestCallBack<String> callBack)
            throws IOException {
        RequestParams params = new RequestParams();
        Set<String> keySet = param.keySet();
        params.addBodyParameter("filetype", fileType);
        for (String key : keySet) {
            if (param.get(key) instanceof Bitmap) {// 当参数是Bitmap时处理方式
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                CompressFormat format = CompressFormat.JPEG;
                Bitmap bitmap = (Bitmap) param.get(key);
                bitmap.compress(format, 100, bos);
                InputStream is = new ByteArrayInputStream(bos.toByteArray());
                params.addBodyParameter(key, is, is.available());
            } else if (param.get(key) instanceof File) {
                ByteArrayOutputStream bos = getBytes((File) param.get(key));
                InputStream is = new ByteArrayInputStream(bos.toByteArray());
                params.addBodyParameter(key, is, is.available());
            } else {
                params.addBodyParameter(key, (String) param.get(key));
            }
        }
        HttpUtils hu = new HttpUtils();
        hu.send(HttpMethod.POST, url, params, callBack);
    }

    /**
     * 获得指定文件的byte数组
     */
    public static ByteArrayOutputStream getBytes(File file) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bos;
    }



	public static void getRequest(final List<NameValuePair> pairs,
			final String url, final NetWorkCallBack callBack) {
		RequestParams params = new RequestParams();
		StringBuffer content = new StringBuffer();
		if (pairs != null && pairs.size() > 0) {
			for (int i = 0; i < pairs.size(); i++) {
				if (i == 0)
					content.append("?" + pairs.get(i).getName() + "="
							+ pairs.get(i).getValue());
				else
					content.append("&" + pairs.get(i).getName() + "="
							+ pairs.get(i).getValue());
			}
		}
//        LoggerUtils.getLog(NetWorkUtils.class).error(url + content.toString());
//		URL uri = new URL(url + content.toString());
		HttpUtils hu = new HttpUtils();
//		hu.configTimeout(5000);
//		LoggerUtils.getLog(NetWorkUtils.class).error(url+content.toString());
		hu.configCurrentHttpCacheExpiry(0);
		hu.send(HttpMethod.GET, url + content.toString(), params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				callBack.success(responseInfo.result);
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				callBack.error(msg);
			}
		});
//		Future<String> future = executor.submit(new Callable<String>() {
//			@Override
//			public String call() throws Exception {
//				StringBuffer content = new StringBuffer();
//				if (pairs != null && pairs.size() > 0) {
//					for (int i = 0; i < pairs.size(); i++) {
//						if (i == 0)
//							content.append("?" + pairs.get(i).getName() + "="
//									+ pairs.get(i).getValue());
//						else
//							content.append("&" + pairs.get(i).getName() + "="
//									+ pairs.get(i).getValue());
//					}
//				}
//				URL uri = new URL(url + content.toString());
//				HttpURLConnection conn = (HttpURLConnection) uri
//						.openConnection();
//				conn.setReadTimeout(5000);
//				conn.setConnectTimeout(5000);
//				conn.setRequestMethod("GET");
//				conn.setRequestProperty("Content-Type",
//						"application/x-www-form-urlencoded");
//				conn.connect();
//				if (conn.getResponseCode() == 200) {
//					InputStream is = conn.getInputStream();
//					// 创建字节输出流对象
//					ByteArrayOutputStream os = new ByteArrayOutputStream();
//					// 定义读取的长度
//					int len = 0;
//					// 定义缓冲区
//					byte buffer[] = new byte[1024 * 4];
//					// 按照缓冲区的大小，循环读取
//					while ((len = is.read(buffer)) != -1) {
//						// 根据读取的长度写入到os对象中
//						os.write(buffer, 0, len);
//					}
//					// 释放资源
//					is.close();
//					os.close();
//					// 返回字符串
//					// String result = new String(os.toByteArray(), "UTF-8");
//					return os.toString();
//				}
//				return null;
//			}
//		});
//		try {
//			String data = future.get();
//			if (data != null)
//				callBack.success(data);
//			else
//				callBack.error();
//		} catch (InterruptedException e) {
//			callBack.error(e.getMessage());
//		} catch (ExecutionException e) {
//			callBack.error(e.getMessage());
//		}
//		executor.execute(new Runnable() {
//			@Override
//			public void run() {
//				try{
//
//					StringBuffer content = new StringBuffer();
//					if (pairs != null && pairs.size() > 0) {
//						for (int i = 0; i < pairs.size(); i++) {
//							if (i == 0)
//								content.append("?" + pairs.get(i).getName() + "="
//										+ pairs.get(i).getValue());
//							else
//								content.append("&" + pairs.get(i).getName() + "="
//										+ pairs.get(i).getValue());
//						}
//					}
//					URL uri = new URL(url + content.toString());
//					HttpURLConnection conn = (HttpURLConnection) uri
//							.openConnection();
//					conn.setReadTimeout(5000);
//					conn.setConnectTimeout(5000);
//					conn.setRequestMethod("GET");
//					conn.setRequestProperty("Content-Type",
//							"application/x-www-form-urlencoded");
//					conn.connect();
//					if (conn.getResponseCode() == 200) {
//						InputStream is = conn.getInputStream();
//						// 创建字节输出流对象
//						ByteArrayOutputStream os = new ByteArrayOutputStream();
//						// 定义读取的长度
//						int len = 0;
//						// 定义缓冲区
//						byte buffer[] = new byte[1024 * 4];
//						// 按照缓冲区的大小，循环读取
//						while ((len = is.read(buffer)) != -1) {
//							// 根据读取的长度写入到os对象中
//							os.write(buffer, 0, len);
//						}
//						// 释放资源
//						is.close();
//						os.close();
//						// 返回字符串
//						callBack.success(os.toString());
//					}
//				}catch (Exception e) {
//					callBack.error(e.getMessage());
//				}
//			}
//		});
	}

    public static void downLoadFile(final String url, final String filePath,
                                    final String fileName, final NetWorkCallBack callBack) {
        Future<String> future = executor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                File file = new File(filePath);
                if (!file.exists())
                    file.mkdir();
                URL uri = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) uri
                        .openConnection();
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
                conn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                conn.connect();
                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    file = new File(fileName);
                    FileOutputStream os = new FileOutputStream(file);
                    byte buff[] = new byte[2 * 1024];
                    int len = -1;
                    while ((len = is.read(buff)) != -1) {
                        os.write(buff, 0, len);
                    }
                    is.close();
                    os.close();
                    return filePath/* + fileName*/;
                }
                return "";
            }
        });
        try {
            String result = future.get();
            if ("".equals(result) || result == null)
                callBack.error();
            else
                callBack.success(result);
        } catch (InterruptedException e) {
            callBack.error(e.getMessage());
        } catch (ExecutionException e) {
            callBack.error(e.getMessage());
        }
    }

    public interface NetWorkCallBack {
        /**
         * 返回值不为空时调用
         */
        void success(String result);

        /**
         * 返回值为空时调用
         */
        void error();

        /**
         * 异常时调用
         */
        void error(String message);
    }
}